import React, { Component } from 'react';
import {
  StyleSheet, Text, View, TouchableOpacity, Image, FlatList, TextInput, PixelRatio
} from "react-native";
import { GLOBAL } from '../../../config/global';
import { API, API_GENERATE } from '../../../config/api';
import HTTP from '../../../utils/http';
import { Common } from '../../../component/common/Common.js';
import { style } from '../../../theme/style';
import { ScrollView } from 'react-navigation';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { DorenCard } from '../_components/DorenCard';
import { ApprovalCpt } from '../_components/ApprovalCpt';
import ToastUtil from '../../../utils/toast';
import { RefuseModal } from '../../../component/ModalVerifylComponent.js';
import navigationSeevice from '../../../components/navigation/navigationSeevice';

const scale = GLOBAL.SCALE;
const searchIcon = require('../../../imgs/global/whiteSearch.png');
const select = require('../../../imgs/select.png');
const TAB_LIST = [
  {
    name: '报盘统计',
    id: 'a',
  },
  {
    name: '报盘概览',
    id: 'b',
  },
  {
    name: '报盘明细',
    id: 'c',
  }
];
const OFFER_STATUS_LIST = [
  {
    dictName: '综合排序',
    dictKey: 0
  }, {
    dictName: '按执行量升序',
    dictKey: 1
  }, , {
    dictName: '按执行量降序',
    dictKey: 2
  }, {
    dictName: '按报盘金额升序',
    dictKey: 3
  }, {
    dictName: '按报盘金额降序',
    dictKey: 4
  }
]

export class OfferSituation extends Component {
  static navigationOptions = ({ navigation, navigationOptions }) => {
    let { tabIndex, headTitle } = navigation.state.params || {};
    return {
      headerTitle: '报盘情况',
      headerTintColor: style.color.white,
      headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
      headerRight: (<Image style={style.head.headRightEmpty} source={require('../../../imgs/goBackEmpty.png')} />),
      headerStyle: {  // 头部整体样式 
        elevation: 0,
        borderBottomWidth: 0,
        backgroundColor: style.color.themeColor
      },
      headerTitleStyle: {
        flex: 1,
        textAlign: 'center'
      }
    }
  };

  /*
    控制页面的参数
    {
      applyId : '', 成交记录的详情页面用 ,底部是3行
      isEidt : '', 多伦勾选用 多伦成交审批页面
      type : 'APPROVE' // 审批详情用 有4个 tab
    }
  */

  constructor(props) {
    super(props)
    let { tabIndex, bidPackageId, isEidt, salesType, bizModel, periodNum, applyId, listData } = props.navigation.state.params || {};
    console.log('props.navigation.state.params', props.navigation.state.params)
    this.salesType = salesType;
    this.bizModel = bizModel;
    this.tabIndex = tabIndex || 0;
    this.periodNum = periodNum;//提交按钮用
    this.isEidt = isEidt || false; // 代表是多伦成交的操作页面
    this.applyId = applyId; // 这个可以用来判断 成交记录的详情
    this.listData = listData || {};
    this.state = {
      status: 'loading',
      options: [],
      isModal: false,
      isCommentsModal: false,
      resData: {
        bidStatisticsTO: {},
        resourceBidList: []
      },
      selectIndex: 0,
      isAll: false,
      showRejectModal: false,//原因输入弹框
    }

    this.pageParams = { // TODO
      bidPackageId: bidPackageId || null,
      applyId: applyId || null,
      searchKey: '',
      sort: 0,
    }
  }

  async componentWillMount() {
    // await this.getSorage();
    await this.initPage();
  }

  async initPage() {
    this.setState({
      status: 'loading',
    })

    let resData;
    let url = (this.isEidt || this.applyId) ? API.PACKAGE_MORE_LIST : API.RESOURECE_APPLY;
    if (this.tabIndex === 0) {
      resData = await HTTP.POST(API_GENERATE(url), this.pageParams)
    }
    else if (this.tabIndex === 1) {
      resData = await HTTP.POST(API_GENERATE(API.RESOURECE_APPLY_LIST), this.pageParams)
    }

    console.log(resData)
    if (resData) {
      if (this.isEidt && this.tabIndex === 0 && resData.resourceBidList && resData.resourceBidList.length) {// 成交勾选用 
        resData.resourceBidList && resData.resourceBidList.map((item, index) => {
          item.checked = false;
          item.index = index;
          return item;
        })
      }
      if (this.tabIndex === 1 && resData.length === 0) {
        this.setState({
          status: 'empty',
          isAll: false
        })
      }
      else {
        this.setState({
          resData,
          status: 'data',
          isAll: false
        })
      }
    }
    else {
      this.setState({
        state: 'error'
      })
    }

  }

  onErrorRefresh = () => {
    this.initPage();
  }

  // 刷新页面
  reloadPage = () => {
    this.initPage();
  }


  changeTab(index) {
    if (this.tabIndex === index) return;
    if (index === 2) {
      this.props.navigation.navigate('OfferDetail', { headTitle: '报盘明细', bidPackageId: this.pageParams.bidPackageId, type: 'unlimited', applyId: this.applyId })
    }
    else {
      this.tabIndex = index;
      this.pageParams.searchKey = '';
      this.props.navigation.setParams({
        headTitle: TAB_LIST[index].name
      })
      this.reloadPage();
    }
  }

  _selectCallBack = (index) => {
    this.setState({
      isModal: false,
      selectIndex: index,
    }, () => {
      this.pageParams.sort = OFFER_STATUS_LIST[this.state.selectIndex].dictKey;
      this.reloadPage();
    })
  }

  // 搜索View
  _renderFilterWrap() {
    let { selectIndex } = this.state
    return (
      <View style={styles.filterWrap}>
        <View style={{ flex: 1 }}>
          <Image source={searchIcon} style={styles.searchIcon} />
          <TextInput
            ref="enterpriseInput"
            style={styles.searchInput}
            underlineColorAndroid='transparent'
            placeholder={"请输入企业/商品"}
            placeholderTextColor="rgba(255, 255, 255, .8)"
            maxLength={30}
            returnKeyType={'search'}
            defaultValue={this.pageParams.searchKey}
            onChangeText={(txt) => { this.pageParams.searchKey = txt; }}
            onSubmitEditing={() => { this.reloadPage(); }}
          />
        </View>
        {this.tabIndex === 1 ?
          <TouchableOpacity onPress={() => { this.setState({ isModal: true }) }}
            style={{ paddingLeft: 20 * scale, flexDirection: "row", alignItems: "center", height: 36 * scale }}>
            <Text style={{ color: "#fff", marginRight: 5 }}>{OFFER_STATUS_LIST[selectIndex].dictName}</Text>
            <Image source={select} style={{ width: 10, height: 5, tintColor: '#fff' }} />
          </TouchableOpacity> : null
        }

      </View>
    )
  }

  _offerStatistics() {
    let { resData, status } = this.state
    let { resourceBidList, bidStatisticsTO, resourceBidBargainApplyVO } = resData
    return (
      <ScrollView style={[styles.offerBox, this.isEidt ? styles.offerBoxActive : null]}>
        {
          status == 'data' ?
            <View>
              {resourceBidList && resourceBidList.map((item, index) => {
                return (
                  <DorenCard applyId={this.applyId} salesType={this.salesType} key={index} itemData={item} callBack={this._itemCallback} />
                )
              })
              }
              {bidStatisticsTO && !this.applyId ?
                <View style={{ marginTop: 25 * scale }}>
                  <View style={styles.offerData}>
                    <Text>上架时间：{bidStatisticsTO.upTime || '-'}</Text>
                  </View>
                  <View style={styles.offerData}>
                    <Text>下架时间：{bidStatisticsTO.removeTime || '-'}{bidStatisticsTO.diffTime ? '（持续时间：' + bidStatisticsTO.diffTime + '）' : null}</Text>
                  </View>
                  <View style={styles.offerData}>
                    <Text>是否转成交：{bidStatisticsTO.isMustTran === 'Y' ? '是' : '否'}</Text>
                    {bidStatisticsTO.isMustTran === 'Y' ?
                      <TouchableOpacity style={{ paddingVertical: 5 * scale }} onPress={() => { this.props.navigation.navigate('ToClaimList', { searchKey: bidStatisticsTO.bidPackageId, beginDate: null, endDate: null, checkedAll: false, checkedAll2: false }) }}>
                        <Text style={{ color: '#0091FF' }}>【查看认领情况】</Text>
                      </TouchableOpacity> : null
                    }
                  </View>
                  <View style={styles.offerData}>
                    <Text>资源包编号：{bidStatisticsTO.bidPackageId}</Text>
                  </View>
                </View> : null
              }
              {
                resourceBidBargainApplyVO ? <View style={{ marginTop: 25 * scale }}>
                  <View style={styles.offerData}>
                    <Text>申请人：{resourceBidBargainApplyVO.createByName || '-'}({resourceBidBargainApplyVO.teamName || '-'})</Text>
                  </View>
                  <View style={styles.offerData}>
                    <Text>申请时间：{resourceBidBargainApplyVO.createTime || '-'}</Text>
                  </View>
                  <View style={styles.offerData}>
                    <Text>申请原因：{resourceBidBargainApplyVO.comments || '-'}</Text>
                  </View>
                </View> : null
              }
            </View> : (<View style={{ flex: 1, marginTop: 150 * scale }}>
              <PageStatusIndex status={status} emptyText="暂无记录" onErrorPress={this.onErrorRefresh} />
            </View>)
        }

      </ScrollView>
    )
  }
  _offerOverview() {
    let { resData, status } = this.state
    console.log(resData)
    return (
      <ScrollView style={[styles.offerBox, this.isEidt ? styles.offerBoxActive : null]}>
        {
          status == 'data' ?
            <View style={styles.offerOverview}>
              <View style={{ flexDirection: 'row' }}>
                <View style={styles.offerContentItem}>
                  <Text style={styles.offerItemTitle}>
                    商品
                </Text>
                </View>
                <View style={styles.offerContentItem}>
                  <Text style={styles.offerItemTitle}>
                    单价（元/吨）
                </Text>
                </View>
                <View style={styles.offerContentItem}>
                  <Text style={styles.offerItemTitle}>
                    有效报盘（吨）
                </Text>
                </View>
                <View style={styles.offerContentItem}>
                  <Text style={styles.offerItemTitle}>
                    已生效（吨）
                </Text>
                </View>
              </View>
              {resData.length > 0 ? resData.map((item, index) => {
                return (
                  <View style={styles.offerContent} key={index}>
                    <View style={styles.offerTitleBox}>
                      <Text style={{ fontSize: 10 * scale }}>
                        {item.companyName}
                      </Text>
                    </View>
                    {item.appOrderResourceVTOList.length > 0 ? item.appOrderResourceVTOList.map((itemResource, indexResource) => {
                      return (
                        <View style={{ flexDirection: 'row', marginTop: 5 * scale }} key={indexResource}>
                          <TouchableOpacity style={styles.offerResourceTitle} onPress={() => { this.setState({ isCommentsModal: true, goodsName: itemResource.goodsName }) }}>
                            <Text style={styles.offerResourceTitleText} numberOfLines={1}>
                              {itemResource.goodsName}
                            </Text>
                          </TouchableOpacity>
                          <View style={{ flex: 1 }}>
                            {itemResource.appOrderNumList.length > 0 ? itemResource.appOrderNumList.map((itemNum, indexNum) => {
                              return (
                                <View style={styles.resourceContent} key={indexNum}>
                                  <View style={styles.offerContentItem}>
                                    <Text style={styles.offerItemTitle}>
                                      {itemNum.priceType === 1 ? (itemNum.price ? '¥' + itemNum.price : itemNum.offerBottomPrice ? '¥' + itemNum.offerBottomPrice : '-') : (itemNum.udPrice ? '¥' + itemNum.udPrice : '-')}
                                    </Text>
                                  </View>
                                  {itemNum.sumQuantity ?
                                    <TouchableOpacity style={styles.offerContentItem} onPress={
                                      () => {
                                        this.props.navigation.navigate('OfferDetail',
                                          { headTitle: '有效报盘明细', bidPackageId: this.pageParams.bidPackageId, resourceId: itemNum.resourceId, status: [1, 2, 5, 6, 7], type: 'limited' })
                                      }}>
                                      <Text style={[styles.offerItemTitle, { color: '#0091FF' }]}>
                                        {itemNum.sumQuantity}
                                      </Text>
                                    </TouchableOpacity> :
                                    <View style={styles.offerContentItem}>
                                      <Text style={[styles.offerItemTitle]}>
                                        -
                              </Text>
                                    </View>
                                  }
                                  {itemNum.sumIntentionQuantity ?
                                    <TouchableOpacity style={styles.offerContentItem} onPress={
                                      () => {
                                        this.props.navigation.navigate('OfferDetail', {
                                          headTitle: '已生效报盘明细', bidPackageId: this.pageParams.bidPackageId, resourceId: itemNum.resourceId, status: [5, 6, 7], type: 'limited'
                                        })
                                      }}>
                                      <Text style={[styles.offerItemTitle, { color: '#0091FF' }]}>
                                        {itemNum.sumIntentionQuantity}
                                      </Text>
                                    </TouchableOpacity> :
                                    <View style={styles.offerContentItem}>
                                      <Text style={[styles.offerItemTitle]}>
                                        -
                                </Text>
                                    </View>
                                  }

                                </View>
                              )
                            })
                              : null
                            }
                          </View>

                        </View>
                      )
                    }) : null
                    }

                  </View>
                )
              }) : null
              }

            </View> : (<View style={{ flex: 1, marginTop: 150 * scale }}>
              <PageStatusIndex status={status} emptyText="暂无记录" onErrorPress={this.onErrorRefresh} />
            </View>)
        }

      </ScrollView>
    )
  }

  //tab View
  _renderTabWrap = () => {
    return (
      <View style={[styles.tabWrap, this.isEidt ? styles.tabWrapActive : null]}>
        {
          TAB_LIST.map((item, index) => {
            return (
              <TouchableOpacity activeOpacity={1} onPress={() => { this.changeTab(index) }} key={index} style={styles.tabItem}>
                <Text style={[styles.tabText, this.tabIndex == index ? { fontWeight: 'bold' } : { opacity: .8 }]}>{item.name}</Text>
                <View style={[styles.tabTextBottom, this.tabIndex == index ? { backgroundColor: '#fff' } : { backgroundColor: 'transparent' }]}></View>
              </TouchableOpacity>
            )
          })
        }
      </View>
    )
  }

  //全选方法
  _selectAll = (isAll) => {
    let { resData } = this.state;
    let { resourceBidList } = resData;
    if (resourceBidList && resourceBidList.length) {
      resourceBidList.map((item) => {
        if (item.canOperateData != "N") {
          item.checked = isAll;
        }
        return item;
      })
    }
    this.setState({
      isAll,
      resData
    })
  }

  //获取以勾选的像
  _getCheck = () => {
    let { resData } = this.state;
    let { resourceBidList } = resData;
    let result = [];
    if (resourceBidList && resourceBidList.length) {
      let chekList = resourceBidList.filter(item => item.checked);
      if (chekList && chekList) {
        chekList.forEach(item => {
          result.push({ resourceId: item.resourceId, goodsSkuId: item.goodsSkuId })
        })
      }
    }
    return result;
  }

  //展示弹框
  _showAlert = async () => {
    let { resData } = this.state;
    let { resourceBidList, bidStatisticsTO } = resData;
    if (resourceBidList && !resourceBidList.some(item => item.checked)) {
      ToastUtil.showWarning("请先勾选");
      return;
    }
    let params = {
      applyInfo: { applyType: this.auditResult, bizModel: this.bizModel, bidPackageId: bidStatisticsTO.bidPackageId, periodNum: this.periodNum, salesType: this.salesType },
      itemList: this._getCheck()
    }

    let respones = await HTTP.POST(API_GENERATE(API.PACKAGE_TOAST), params);

    if (respones) {
      this.priceCheckMsg = respones.priceCheckMsg
    }

    this.setState({
      showRejectModal: true,
    })
  }

  //成交请求
  _apply = async (comments) => {
    let { resData } = this.state;
    let { bidStatisticsTO } = resData;

    let params = {
      applyInfo: { applyType: this.auditResult, bizModel: this.bizModel, bidPackageId: bidStatisticsTO.bidPackageId, comments, periodNum: this.periodNum, salesType: this.salesType },
      itemList: this._getCheck()
    }
    resData = await HTTP.POST(API_GENERATE(API.PACKAGE_BID_APPLY), params);
    console.log("resData", resData)
    if (resData) {
      ToastUtil.showSuccess(`${this.auditResult === 'ACCEPT' ? '成交' : '拒绝'}成功`).then(() => {
        navigationSeevice.navigate('ClinchRecord', { bizModel: this.bizModel, bidPackageId: bidStatisticsTO.bidPackageId, salesType: this.salesType, listData: this.listData })
      });
    } else {
      this.reloadPage();
    }
  }

  //勾选回调
  _itemCallback = (callData) => {
    console.log("data-回掉", callData);
    if (!callData) return;
    let { resData } = this.state;
    let { resourceBidList } = resData;
    resourceBidList[callData.index] = callData;
    let isAll = resourceBidList.every((item) => item.checked === true);
    this.setState({
      resData,
      isAll
    }, () => {
      console.log("data-回掉-resData", resData);
    })
  }

  //是否有代生效的数据
  _isHash = () => {
    let { resData } = this.state;
    let { resourceBidList } = resData;
    return resourceBidList && resourceBidList.some(item => (item.canOperateData != "N"));
  }

  render() {
    let { selectIndex, isModal, goodsName, isCommentsModal, isAll, showRejectModal } = this.state;
    return (
      <View style={styles.container}>
        {this._renderFilterWrap()}
        {this._renderTabWrap()}
        {this.tabIndex === 0 ? this._offerStatistics() : null}
        {this.tabIndex === 1 ? this._offerOverview() : null}
        <Common type="modal" demoData={(
          <Common type="listRadio" selectIndex={selectIndex} title={'状态'} listData={OFFER_STATUS_LIST} selectCallBack={this._selectCallBack} />
        )} isVisible={isModal} closeCallballFn={() => { this.setState({ isModal: false }) }} />
        <Common type="modal" demoData={(
          <View style={styles.commentsBody}>
            <Text style={styles.commentsTitle}>商品名称</Text>
            <Text style={styles.commentContent}>{goodsName}</Text>
          </View>
        )} isVisible={isCommentsModal} closeCallballFn={() => { this.setState({ isCommentsModal: false }) }} />
        {
          (this.isEidt && this.tabIndex === 0 && this._isHash()) ?
            <ApprovalCpt data={{ isAll }} method={{ selectAll: this._selectAll, refused: () => { this.auditResult = 'REJECT'; this._showAlert() }, agree: () => { this.auditResult = 'ACCEPT'; this._showAlert() } }} />
            : null
        }
        <RefuseModal
          titleText={'申请原因'}
          placeholderText={'请输入原因'}
          visible={showRejectModal}
          text={this.priceCheckMsg}
          btnPress={(text) => {
            this.setState({
              showRejectModal: false,
            }, () => {
              this._apply(text);
            })
          }}
          bgPress={() => {
            this.setState({
              showRejectModal: false,
            });
          }} />
      </View>
    )
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: style.color.bgGray,
  },
  filterWrap: {
    height: 36 * scale,
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 30 * scale,
    backgroundColor: style.color.themeColor,
  },
  searchInput: {
    flex: 1,
    width: '100%',
    paddingLeft: 50 * scale,
    paddingRight: 12 * scale,
    backgroundColor: 'rgba(255, 255, 255, .18)',
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    paddingVertical: 0,
    position: 'relative',
    borderRadius: 8 * scale,
    color: '#fff',

  },
  searchIcon: {
    width: 20 * scale,
    height: 22 * scale,
    position: 'absolute',
    left: 20 * scale,
    top: 8 * scale,
    zIndex: 9,
    opacity: 0.8,
  },
  tabWrap: {
    backgroundColor: style.color.themeColor,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'flex-start',
    paddingLeft: 18 * scale,
    paddingRight: 18 * scale,
    paddingBottom: 150 * scale
  },
  tabWrapActive: {
    paddingBottom: 0 * scale
  },
  tabText: {
    color: '#fff',
    textAlign: 'center'
  },
  tabTextBottom: {
    marginTop: 7 * scale,
    height: 2 * scale,
    width: '100%'
  },
  tabItem: {
    paddingTop: 14 * scale,
    paddingBottom: 12 * scale,
    paddingHorizontal: 30 * scale,
  },
  offerBox: {
    flex: 1,
    marginTop: -150 * scale,
    marginHorizontal: 20 * scale
  },
  offerBoxActive: {
    marginTop: 20 * scale,
  },
  offerItem: {
    backgroundColor: '#fff',
    paddingVertical: 14 * scale,
    paddingHorizontal: 20 * scale,
    borderRadius: 6 * scale,
    marginBottom: 14 * scale
  },
  offerTitle: {
    fontSize: 13,
    color: '#000000',
    fontWeight: "600"
  },
  offerContent: {
    marginTop: 7 * scale,
    backgroundColor: '#F4F7FE',
    borderRadius: 6 * scale,
    paddingVertical: 10 * scale,
  },
  offerHorizontal: {
    flexDirection: "row",
    alignItems: 'center',
    marginBottom: 25 * scale
  },
  offerContentItem: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  offerItemTitle: {
    flex: 1,
    fontSize: 11 * scale,
    paddingTop: 5 * scale,
    marginBottom: 5 * scale,
  },
  offerItemText: {
    fontSize: 11 * scale,
  },
  offerData: {
    marginBottom: 8 * scale,
    flexDirection: 'row',
    alignItems: 'center'
  },
  offerOverview: {
    backgroundColor: '#fff',
    paddingVertical: 14 * scale,
    paddingHorizontal: 10 * scale,
    borderRadius: 6 * scale
  },
  offerTitleBox: {
    marginHorizontal: 20 * scale,
    marginTop: 5 * scale,
    paddingBottom: 10 * scale,
    borderColor: '#979797',
    borderBottomWidth: 1 / PixelRatio.get(),
    marginBottom: 5 * scale
  },
  offerResourceTitle: {
    width: 100 * scale,
    paddingLeft: 20 * scale,
    marginTop: 5 * scale
  },
  offerResourceTitleText: {
    fontSize: 11,
    color: '#0091FF',
    flexWrap: 'nowrap',
  },
  resourceContent: {
    flex: 1,
    flexDirection: 'row'
  },
  commentsBody: {
    width: 300 * scale,
    paddingLeft: 25 * scale,
    paddingRight: 17 * scale,
    paddingBottom: 30 * scale,
    backgroundColor: '#fff',
    borderRadius: 13 * scale
  },
  commentsTitle: {
    fontSize: 12 * scale,
    color: style.color.darkGray,
    paddingTop: 15 * scale,
    paddingBottom: 15 * scale
  },
  commentContent: {
    fontSize: 12 * scale,
    paddingTop: 15 * scale,
    paddingBottom: 15 * scale
  }
})